<?php

/**
 * This is the model class for table "blog".
 *
 * The followings are the available columns in table 'blog':
 * @property string $id
 * @property string $title
 * @property string $discription
 * @property string $thumbnail
 * @property string $create_time
 * @property string $update_time
 * @property integer $category
 * @property integer $artist
 */
class Blog extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @return Blog the static model class
     */
    public $thumbnail_file;
    public $thumbnail_file_2;
    public $thumbnail_file_3;
    public $thumbnail_file_4;
    public $thumbnail_file_5;
    public $blog_home;
    public $show_home;
    public $home_show;
    public $recommend;
    public $type = 'blog';

    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'blog';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, category, home_show, recommend', 'required'),
            array('category, artist', 'numerical', 'integerOnly' => true),
            array('title, tag, thumbnail', 'length', 'max' => 255),
            array('discription', 'safe'),
            //array('thumbnail', 'types'=>'jpg, gif, png, jpeg'),
            array('thumbnail_file,thumbnail_file_2,thumbnail_file_3,thumbnail_file_4,thumbnail_file_5', 'file', 'allowEmpty' => true,
                'types' => 'jpg, gif, png, jpeg',
                'maxSize' => 1024 * 1024 * 10, // 10MB
                'tooLarge' => 'The file was larger than 10MB. Please upload a smaller file.',
            ),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, tag, discription, thumbnail, create_time, update_time, category, artist', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'category_name' => array(self::BELONGS_TO, 'BlogCategory', 'category'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'title' => 'Title',
            'discription' => 'Content',
            'thumbnail' => 'Thumbnail',
            'thumbnail_file' => 'Thumbnail File 1',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'category' => 'Category',
            'artist' => 'Artist',
            'tag' => 'Tags',
            'home_show' => 'Show on Front Page',
            'recommend' => 'Recommend'
        );
    }

    public function getUrl() {
        return Yii::app()->createUrl('blog/view', array('id' => $this->id, 'title' => $this->title));
    }

    public function getArtistName() {
        $artist = Artist::model()->findByPk($this->artist);
        return $artist->name;
    }

    public function getCategoryName() {
        $category = BlogCategory::model()->findByPk($this->category);
        if ($category != null) {
            return $category->name;
        }
        return null;
    }

    public function beforeSave() {
        if ($this->artist == 0) {
            $this->artist = null;
        }
        $this->update_time = date('Y-m-d H:i:s', time());
        //$this->makeThumbName();
        $this->uploadImage();
        return true;
    }

    public function afterSave() {
        if ($this->show_home != null) {
            $home_model = Home::model()->findByPk($this->show_home);
            $home_model->type = 'blog';
            $home_model->owner = $this->id;
            $home_model->save();
        }
        //$this->makeThumbFile();
        $this->addSearch();
        if ($this->blog_home) {
            $blog_home = BlogHome::model()->findByPk(0);
            $blog_home->blog = $this->id;
            $blog_home->save();
        }
    }

    public function addSearch() {
        $search_model = SearchAll::model()->findByAttributes(array('type' => 'blog', 'real_id' => $this->id));
        if ($search_model) {
            $search_model->short = $this->title;
            $search_model->save();
        } else {
            $search_model = new SearchAll;
            $search_model->short = $this->title;
            $search_model->type = 'blog';
            $search_model->real_id = $this->id;
            $search_model->save();
        }
    }

    public function beforeDelete() {
        if ($this->thumbnail != null) {
            $thumb_array = explode(",", $this->thumbnail);
            foreach ($thumb_array as $value) {
                $path_parts = pathinfo($value);
                $pos = strrpos($path_parts["basename"], ".");
                $ext = substr($path_parts["basename"], $pos);
                $file_name = str_replace($ext, '', $path_parts["basename"]);
                $thumb_path = $path_parts["dirname"] . '/' . $file_name . '_thumb.' . $path_parts["extension"];
                if (file_exists($thumb_path)) {
                    unlink($thumb_path);
                }
                if (file_exists($value)) {
                    unlink($value);
                }
            }
        }
        return true;
    }

    public function makeThumbName() {
        $model = $this->model();
        $thumbnail = CUploadedFile::getInstance($model, 'thumbnail_file');
        if ($thumbnail != null) {
            $today = getdate();
            $month = $today['mon'];
            $day = $today['mday'];
            $year = $today['year'];
            $upload_path = Yii::app()->params['media_dir'] . '/' . $year . '/' . $month . '/' . $day . '/';
            $upload_name = time();
            $image_path = $upload_path . $upload_name . '.' . CUploadedFile::getInstance($model, 'thumbnail_file')->extensionName;
            $this->thumbnail = $image_path;
            if (!file_exists($upload_path)) {
                if (!Tool::mkpath($upload_path)) {
                    echo('Make directory error');
                    exit;
                }
            }
        }
    }

    public function makeThumbFile() {
        $model = $this->model();
        $thumbnail = CUploadedFile::getInstance($model, 'thumbnail_file');
        if ($thumbnail != null) {

            $thumbnail->saveAs($this->thumbnail);

            $path_parts = pathinfo($this->thumbnail);
            $pos = strrpos($path_parts["basename"], ".");
            $ext = substr($path_parts["basename"], $pos);
            $file_name = str_replace($ext, '', $path_parts["basename"]);
            $thumb = $path_parts["dirname"] . '/' . $file_name . '_thumb.' . $path_parts["extension"];
            /* ImageHelper::thumb(Yii::app()->params['blog_width'], Yii::app()->params['blog_height'], $this->thumbnail, array(
              'method' => 'adaptiveResize',
              'quality' => 90), $this->thumbnail
              ); */
            ImageHelper::thumb(Yii::app()->params['thumb_width'], Yii::app()->params['thumb_height'], $this->thumbnail, array(
                'method' => 'adaptiveResize',
                'quality' => 90), $thumb
            );
        }
    }

    public function uploadImage() {
        $model = $this->model();
        $images = array('thumbnail_file', 'thumbnail_file_2', 'thumbnail_file_3', 'thumbnail_file_4', 'thumbnail_file_5');
        foreach ($images as $value) {
            $image = CUploadedFile::getInstance($model, $value);
            $this->uploadOneImage($image);
        }
    }

    public function uploadOneImage($image) {
        if ($image != null) {
            $today = getdate();
            $month = $today['mon'];
            $day = $today['mday'];
            $year = $today['year'];
            $upload_path = Yii::app()->params['media_dir'] . '/' . $year . '/' . $month . '/' . $day . '/';
            $upload_name = md5($image->name) . time();
            $image_path = $upload_path . $upload_name . '.' . $image->extensionName;
            if (!file_exists($upload_path)) {
                if (!Tool::mkpath($upload_path)) {
                    echo('Make directory error');
                    exit;
                }
            }
            if ($this->thumbnail != null) {
                $thumb_array = explode(",", $this->thumbnail);
            } else {
                $thumb_array = array();
            }
            $thumb_array[] = $image_path;
            $thumb_str = implode(",", $thumb_array);
            $this->thumbnail = $thumb_str;
            $image->saveAs($image_path);
            $path_parts = pathinfo($image_path);
            $pos = strrpos($path_parts["basename"], ".");
            $ext = substr($path_parts["basename"], $pos);
            $file_name = str_replace($ext, '', $path_parts["basename"]);
            $thumb = $path_parts["dirname"] . '/' . $file_name . '_thumb.' . $path_parts["extension"];
            ImageHelper::thumb(Yii::app()->params['thumb_width'], Yii::app()->params['thumb_height'], $image_path, array(
                'method' => 'adaptiveResize',
                'quality' => 90), $thumb
            );
        }
    }

    public function getThumb() {
        if ($this->thumbnail != null) {
            $thumb_array = explode(",",$this->thumbnail);
            $image_parts = pathinfo(current($thumb_array));
            return Yii::app()->baseUrl . '/' . $image_parts["dirname"] . '/' . $image_parts["filename"] . '_thumb.' . $image_parts["extension"];
        } else {
            return Yii::app()->baseUrl . '/images/no_image.jpg';
        }
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('discription', $this->discription, true);
        $criteria->compare('thumbnail', $this->thumbnail, true);
        $criteria->compare('create_time', $this->create_time, true);
        $criteria->compare('update_time', $this->update_time, true);
        $criteria->compare('category', $this->category);
        $criteria->compare('artist', $this->artist);

        return new CActiveDataProvider(get_class($this), array(
            'criteria' => $criteria,
        ));
    }

}